/*
 * @Author: Await
 * @Date: 2025-02-23 11:05:33
 * @LastEditors: Await
 * @LastEditTime: 2025-02-23 11:08:07
 * @Description: 请填写简介
 */
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

// 获取包信息
const packageJson = require('../package.json');
const extensionName = packageJson.name;
const version = packageJson.version;

// 创建输出目录
const outputDir = path.join(__dirname, '../dist');
if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir);
}

// 创建 VSIX 包
const vsixPath = path.join(outputDir, `${extensionName}-${version}.vsix`);
const output = fs.createWriteStream(vsixPath);
const archive = archiver('zip', {
    zlib: {
        level: 9
    }
});

output.on('close', () => {
    console.log(`打包完成: ${vsixPath}`);
    console.log(`包大小: ${(archive.pointer() / 1024 / 1024).toFixed(2)} MB`);
});

archive.on('error', (err) => {
    throw err;
});

archive.pipe(output);

// 添加必要文件
const filesToInclude = [{
        source: 'package.json',
        target: 'extension/package.json'
    },
    {
        source: 'README.md',
        target: 'extension/README.md'
    },
    {
        source: 'LICENSE',
        target: 'extension/LICENSE'
    },
    {
        source: 'out',
        target: 'extension/out'
    },
    {
        source: 'node_modules/@vscode/debugadapter',
        target: 'extension/node_modules/@vscode/debugadapter'
    },
    {
        source: 'node_modules/@vscode/debugprotocol',
        target: 'extension/node_modules/@vscode/debugprotocol'
    }
];

// 添加文件到压缩包
for (const file of filesToInclude) {
    const sourcePath = path.join(__dirname, '..', file.source);
    if (fs.existsSync(sourcePath)) {
        const stats = fs.statSync(sourcePath);
        if (stats.isDirectory()) {
            archive.directory(sourcePath, file.target);
        } else {
            archive.file(sourcePath, {
                name: file.target
            });
        }
    } else {
        console.warn(`警告: 文件或目录不存在: ${sourcePath}`);
    }
}

// 创建扩展清单
const manifestContent = {
    name: packageJson.name,
    displayName: packageJson.displayName,
    description: packageJson.description,
    version: packageJson.version,
    publisher: packageJson.publisher,
    engines: packageJson.engines,
    categories: packageJson.categories,
    activationEvents: packageJson.activationEvents,
    main: packageJson.main,
    contributes: packageJson.contributes
};

archive.append(JSON.stringify(manifestContent, null, 2), {
    name: 'extension/extension.vsixmanifest'
});

// 完成打包
archive.finalize();